import { _decorator, Component, Node, ProgressBar, UIOpacity, Vec3, UICoordinateTracker, Camera, v3, size, Sprite, Color, color } from 'cc';
import { BasicComponet } from '../../Init/Basic/BasicComponet';
import { GlobalEnum } from '../../Init/Config/GlobalEnum';
import GlobalPool from '../../Init/Tools/GlobalPool';
const { ccclass, property } = _decorator;

@ccclass('hpBar')
export class hpBar extends BasicComponet {
    data: { isShow: boolean, rate: number, curRate: number, isPlayer: boolean, wpos: Vec3, type: number, isHide: boolean } = null;

    @property(ProgressBar)
    pb: ProgressBar = null;
    @property(UIOpacity)
    uiOpacity: UIOpacity = null;
    _camera: Camera = null;

    barSp: Sprite = null;
    hideIco: Node = null;
    bg: Node = null;

    setData(d: { data, camera: Camera, parent: Node }) {
        this.data = d.data;
        this.pb.progress = 1.0;
        this.uiOpacity.opacity = 255;
        this._camera = d.camera;
        this.node.parent = d.parent;
        this.bg = this.node.getChildByName('bg');
        this.hideIco = this.node.getChildByName('hideIco');
        this.barSp = this.node.getChildByName('Bar').getComponent(Sprite);
        this.calPos();
    }

    reset() {
        this.pb.progress = 1.0;
        this.uiOpacity.opacity = 255;
        this.hideIco.active = false;
    }

    _colors: Color[] = [color().fromHEX('#FF0303'), color().fromHEX('#03FF17')];
    _tmpPos = v3();

    update(dt) {
        if (this.data && this.data.type == GlobalEnum.HpBarType.player) {
            let isShow = this.data.isShow && this.data.rate < 1 || this.data.curRate != this.data.rate;

            let addRate = (this.data.rate - this.data.curRate) * 0.1 * dt * 60;
            if (Math.abs(addRate) > 0.001) {
                this.data.curRate += addRate;
            } else {
                this.data.curRate = this.data.rate;
            }

            this.pb.progress = this.data.curRate;
            // this.uiOpacity.opacity = isShow ? 255 : 0;
            if (isShow) {
                //颜色
                this.barSp.color = this._colors[this.data.type];
            }
            this.bg.active = isShow;
            this.barSp.node.active = isShow;
            //隐藏标记
            this.hideIco.active = this.data.isHide;
            //计算位置
            this.calPos();

            if (this.data.rate == 0) {
                GlobalPool.put(this.node);
            }
        }
    }

    calPos() {
        this._camera.convertToUINode(this.data.wpos, this.node.parent, this._tmpPos);
        this._tmpPos.y += 90;
        this.node.setPosition(this._tmpPos);
    }
}


